package com.sakura.gateway.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.Getter;
import com.sakura.gateway.props.JwtProperties;

import java.nio.charset.StandardCharsets;
import java.util.Base64;


public class JwtUtil {

    public static String BEARER = "bearer";
    public static String CRYPTO = "crypto";
    public static Integer AUTH_LENGTH = 7;


    @Getter
    private static JwtProperties jwtProperties;

    public static void setJwtProperties(JwtProperties properties) {
        if (JwtUtil.jwtProperties == null) {
            JwtUtil.jwtProperties = properties;
        }
    }


    public static String getBase64Security() {
        return Base64.getEncoder().encodeToString(getJwtProperties().getSignKey().getBytes(StandardCharsets.UTF_8));
    }


    public static String getToken(String auth) {
        if (isBearer(auth) || isCrypto(auth)) {
            return auth.substring(AUTH_LENGTH);
        }
        return null;
    }


    public static Boolean isBearer(String auth) {
        if ((auth != null) && (auth.length() > AUTH_LENGTH)) {
            String headStr = auth.substring(0, 6).toLowerCase();
            return headStr.compareTo(BEARER) == 0;
        }
        return false;
    }


    public static Boolean isCrypto(String auth) {
        if ((auth != null) && (auth.length() > AUTH_LENGTH)) {
            String headStr = auth.substring(0, 6).toLowerCase();
            return headStr.compareTo(CRYPTO) == 0;
        }
        return false;
    }


    public static Claims parseJWT(String jsonWebToken) {
        try {
            return Jwts.parserBuilder().setSigningKey(Base64.getDecoder().decode(getBase64Security())).build().parseClaimsJws(jsonWebToken).getBody();
        } catch (Exception ex) {
            return null;
        }
    }

}
